﻿/**
 * ...
 * @author Sergey Mamyan
 */

package tx.squirrel.neko.core.handler;

import haxe.Stack;
import mtwin.web.Request;
import neko.Lib;
import neko.Web;
import templo.Loader;
import mtwin.web.Handler;
import tx.squirrel.neko.core.model.Config;
import tx.squirrel.neko.core.model.User;
import tx.squirrel.neko.core.model.Session;

class BaseHandler extends Handler<Void> {
	
	var template:Loader;
	var user:User;
	
	public function new() {
		super();
	}
	
	override function prepareTemplate( t:String ) : Void {
		template = new Loader(t);
	}
	
	public function display(?data:Dynamic):Void {
		var tempData:Dynamic = {
			config:Config.data,
			session:Session,
			user:getUser(),
			model:data
		}
		Lib.println(template.execute(tempData));
	}
	
	override public function execute( request:Request, ?pathLevel:Int ) {
		try {
			Session.open();
			super.execute(request, pathLevel);
			Session.close();
		}catch (e:Dynamic) {
			displayError(e);
		}
	}
	
	public function displayError(e:Dynamic):Void {
		prepareTemplate("error.mtt");
		display({error:"Error: "+e,stack:Stack.exceptionStack()});
	}
	
	public function hasUser():Bool {
		return (user != null);
	}
	
	public function setUser(user:Int):Void { 
		this.user = User.manager.get(user);
		Session.data.set("user", this.user.id);
	}
	
	public function unsetUser():Void {
		Session.data.remove("user");
	}
	
	public function getUser():User {
		if (user == null && Session.data!=null) {
			if (Session.data.exists("user")){
				setUser(Session.data.get("user"));
			}
		}
		return user;
	}
	
	override function isLogged() : Bool {
		return getUser() != null;
	}
	
	override function isAdmin() : Bool {
		return getUser() != null;
	}
	
	override function isModerator() : Bool {
		return getUser() != null;
	}
	
	public function argument(i:Int):String {
		return this.request.getPathInfoPart(this.level + i);
	}
	
	public function redirect(url:String):Void{
		Web.redirect(url);
	}
}